#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void Print(int* array, int size)
{
  for(int i = 0; i < size; i++){
    printf("%d ", array[i]);
  }

  printf("\n");
}

void Swap(int* left, int* right)
{
  int tmp = *left;
  *left = *right;
  *right = tmp;
}

void SelectSort(int* array, int size)
{
  int left = 0;
  int right = size - 1;
  while(left < right){
    int maxIndex = left;
    int minIndex = right;
    for(int i = left; i <= right; i++){
      if(array[i] > array[maxIndex]) maxIndex = i;
      if(array[i] < array[minIndex]) minIndex = i;
    }
    Swap(&array[maxIndex], &array[right]); 
    if(right == minIndex) minIndex = maxIndex;
    Swap(&array[minIndex], &array[left]);
    left++; right--;
  }
}

void TestSelectSort()
{
  int* array = (int*)malloc(sizeof(int) * 100);
  if(array == NULL){
    perror("malloc");
    return ;
  }
  for(int i = 0; i < 100; i++){
    array[i] = rand() % 100 + 1;
  }

  SelectSort(array, 100);
  Print(array, 100);
  free(array);
  array = NULL;
}

int main()
{
  srand((unsigned long)time(NULL));
  TestSelectSort();
  return 0;
}
